home *** CD-ROM | disk | FTP | other *** search
/ C/C++ Users Group Library 1996 July / C-C++ Users Group Library July 1996.iso / listings / v_12_06 / allison / merge1.c < prev    next >
C/C++ Source or Header  |  1994-04-08  |  2KB  |  78 lines

  1. LISTING 5 - C implementation of Listing 3
  2.  
  3. /* merge1.c: Merge two sorted files to standard output */
  4.  
  5. #include <stdio.h>
  6. #include <stdlib.h>
  7. #include <string.h>
  8.  
  9. main(int argc, char *argv[])
  10. {
  11.     FILE *f1, *f2;
  12.     char buf1[BUFSIZ], buf2[BUFSIZ];
  13.  
  14.     /* Open files */
  15.     if (argc != 3)
  16.         return EXIT_FAILURE;
  17.     f1 = fopen(argv[1],"r");
  18.     f2 = fopen(argv[2],"r");
  19.     if (!f1 || !f2)
  20.         return EXIT_FAILURE;
  21.  
  22.     /* Do the merge */
  23.     fgets(buf1,BUFSIZ,f1);
  24.     fgets(buf2,BUFSIZ,f2);
  25.     while (!feof(f1) && !feof(f2))
  26.     {
  27.         /* INVARIANT: both buffers have fresh lines */
  28.  
  29.         /* Print and refresh the appropriate line */
  30.         if (strcmp(buf1,buf2) <= 0)
  31.         {
  32.             fputs(buf1,stdout);
  33.             fgets(buf1,BUFSIZ,f1);
  34.         }
  35.         else
  36.         {
  37.             fputs(buf2,stdout);
  38.             fgets(buf2,BUFSIZ,f2);
  39.         }
  40.     }
  41.     /* INVARIANT: At least one file has been exhausted */
  42.  
  43.     /* Empty the remaining file */
  44.     while (!feof(f1))
  45.     {
  46.         /* INVARIANT: buffer-1 has a fresh line */
  47.         fputs(buf1,stdout);
  48.         fgets(buf1,BUFSIZ,f1);
  49.     }
  50.     /* INVARIANT: file1 has been exhausted */
  51.     fclose(f1);
  52.  
  53.     while (!feof(f2))
  54.     {
  55.         /* INVARIANT: buffer-2 has a fresh line */
  56.         fputs(buf2,stdout);
  57.         fgets(buf2,BUFSIZ,f2);
  58.     }
  59.     /* INVARIANT: file2 has been exhausted */
  60.     fclose(f2);
  61.  
  62.     return EXIT_SUCCESS;
  63. }
  64.  
  65. /* Sample execution:
  66. c:>merge1 file1.dat file2.dat
  67. brown
  68. dog
  69. fox
  70. jumped
  71. lazy
  72. over
  73. quick
  74. the
  75. the
  76. */
  77.  
  78.